# @author Cweili
# @version 13-9-6 下午11:52

$ ->
	# 对 href 属性与当前 url 相同的列表项添加 .active
	locationURL = "#{window.location.pathname}#{window.location.search}#{window.location.hash}".substr(1)
	$("ul.nav-list li a").each ->
		if $(@).attr("href").indexOf(locationURL) > -1
			$(@).parent().addClass("active")
			false

	if window.location.hash
		$(".tab-pane").removeClass("active")
		$(".tab-pane##{window.location.hash.substr(1)}").addClass("active")

	$("form button").click (event) ->
		event.preventDefault()

	# ajax 提交 form 并获取结果 json
	$("form").submit (event) ->
		event.preventDefault()
		formValues = $(@).serialize()
		form = $(@)
		$.post($(@).attr("action"), formValues, (data) ->
			showMsg(form, data.message, data.type)
			$(".control-group").removeClass("error")
			if data.error && data.error.length > 0
				$.each data.error, (i, n) ->
					$(".control-group.#{n}").addClass("error")
				$("""input[name="#{data.error[0]}"]""").focus()
			else
				$(":password").val("")
		, "json")

	$('.quit').click (event) ->
		quit()

	setInterval(->
		$.ajax url: "util/heartbeat", error: ->
			closeWindow()
	, 3000)

# 显示信息
showMsg = (location, msg, type) ->
	type = "success" if !type?
	alertDiv = """
<div class="alert alert-#{type}">
	<button type="button" class="close" data-dismiss="alert">&times;</button>
	<h4>#{msg}</h4>
</div>"""
	$(".alert").remove()
	location.after(alertDiv)
	setTimeout(->
		$(".alert").fadeOut(1000)
	, 3000)

# 关闭窗口
closeWindow = ->
	window.opener = null
	window.open("", "_self")
	window.close()

# 退出
quit = ->
	$.ajax url: "util/quit", error: ->
		closeWindow()